package persistentie;


import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Connectie {

    private static Properties databaseProperties;
    
    // Ophalen van de databankgegevens en initialisatie van de driver
    static {
        try {
            databaseProperties = new Properties ();
            InputStream inp = Connectie.class.getResourceAsStream ("/databank.properties");
            databaseProperties.load (inp);
            inp.close ();
        } catch (IOException ex) {
            throw new RuntimeException ("Kon databank niet openen", ex);
        }
        try {
            Class.forName (databaseProperties.getProperty ("driver"));
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException ("Kon databankdriver niet vinden", ex);
        }
    }
	
	private Connection connection;

	/**
	 * @directed true
	 */

	// constructor connects to database
	public Connectie() throws SQLException {

		// establish connection to database
		connection = DriverManager.getConnection(databaseProperties.getProperty ("url"), databaseProperties.getProperty ("user"), databaseProperties.getProperty ("password"));
	}

	public Connection getConnection() {
		return connection;
	}

	public void closeConnection() throws SQLException {
		connection.close();
	}

	public ResultSet executeQuery(String query) throws SQLException, IllegalStateException 
	{
		if (connection == null)
			throw new IllegalStateException("Niet verbonden met de database");
		
		Statement statement = getConnection().createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
		return statement.executeQuery(query);
	}

	public PreparedStatement getPreparedStatement(String query)
			throws SQLException {
		PreparedStatement statement = null;

		statement = getConnection().prepareStatement(query);

		return statement;
	}

}
